# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql


class MusicPipeline(object):
    def __init__(self, *args, **kwargs):
        db = pymysql.connect(host='localhost', user='root', password='123', port=3306, db='music', charset='utf8')
        self.db = db
        self.cursor = db.cursor()
        print('数据库开启')

    def process_item(self, item, spider):
        sql = 'insert into comment(comment, liked_count, comment_time) values({values})'.format(values=','.join(['%s']*3))
        param = [item['comment'], item['liked_count'], item['comment_time']]
        print('数据参数为: ' + str(param))
        try:
            if self.cursor.execute(sql, tuple(param)):
                self.db.commit()
                print('成功插入一条数据')
        except:
            print('数据插入失败')
            self.db.rollback()

    def close_spider(self, spider):
        self.db.close()
        print('数据库关闭')
